#!/bin/bash
#这里可替换为你自己的执行程序，其他代码无需更改
#获取绝对路径
app_abs=$(readlink -f "$0")
app_dir=$(dirname $app_abs)
APP_FULL_NAME=${app_dir}/$2
#日志文件夹名称
LOG_FOLDER=logs
#系统运行环境:local、test、prod等根据应用配置环境名称修改
source ./profileConfig.cfg

#Pinpoint参数
if [ -n "$PINPOINT_PATH" ]; then
  POINT_ARGS="-javaagent:$PINPOINT_PATH -Dpinpoint.applicationName=$APP_NAME-$PROFILES -Dpinpoint.agentId=$APP_NAME-$PROFILES-$APP_PORT"
fi

#Logstash参数
if [ -n "$LOGSTASH_HOST" ]; then
  LOGSTASH_ARGS="-Dlogstash.host=$LOGSTASH_HOST -Dlogstash.port=$LOGSTASH_PORT"
fi

#临时缓存文件
if [ -n "$LOGSTASH_HOST" ]; then
  FILE_TEMP_ARGS="-Djava.io.tmpdir=$FILE_TEMP"
fi

debug(){
   echo "APP_FULL_NAME:$APP_FULL_NAME"
   echo "APP_NAME:$APP_NAME"
   echo "APP_PORT:$APP_PORT"
   echo "PROFILES:$PROFILES"
   echo "NACOS:$NACOS"
   echo "NAMESPACE:$NAMESPACE"
   echo "LOG_PATH:$LOG_PATH"
   echo "JVM:$JVM"
   echo "LOGSTASH_HOST:$LOGSTASH_HOST"
   echo "LOGSTASH_PORT:$LOGSTASH_PORT"
   echo "PINPOINT_PATH:$PINPOINT_PATH"
   echo "POINT_ARGS:$POINT_ARGS"
   echo "LOGSTASH_ARGS:$LOGSTASH_ARGS"
   echo "FILE_TEMP_ARGS:$FILE_TEMP_ARGS"
}

#使用说明，用来提示输入参数
usage() {
    echo "Usage: sh 执行脚本.sh [start|stop|restart|status|debug] appname"
    exit 1
}

#检查程序是否在运行
is_exist(){
  pid=`ps -ef|grep $APP_FULL_NAME|grep -v grep|awk '{print $2}' `
  #如果不存在返回1，存在返回0
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}

#启动方法
start(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_FULL_NAME} is already running. pid=${pid} ."
  else
     #rm -rf $LOG_FOLDER/*
	JAVA_COMMAND="java -jar  $POINT_ARGS $LOGSTASH_ARGS $FILE_TEMP_ARGS $JVM $APP_FULL_NAME --spring.profiles.active=$PROFILES --spring.cloud.nacos.server-addr=$NACOS --spring.cloud.nacos.config.namespace=$NAMESPACE"
	echo "run java command: $JAVA_COMMAND"
	nohup $JAVA_COMMAND > /dev/null 2>&1 &
	echo "${APP_PACKAGE_NAME} is starting"
	sleep 5s
	tail -f $LOG_FOLDER/*
  fi
}

#停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
		echo "${APP_FULL_NAME} is stoped"
  else
    echo "${APP_FULL_NAME} is not running"
  fi
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_FULL_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_FULL_NAME} is NOT running."
  fi
}

#重启
restart(){
  stop
  start
}

#根据输入参数，选择执行对应方法，不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  "debug")
    debug
    ;;
  *)
    usage
    ;;
esac
